package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        ListNode listNode = new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))));
//        System.out.println(Arrays.toString(main.reverseBookList(listNode)));
        System.out.println(Arrays.toString(main.reverseBookList2(listNode)));
    }

    /*
     * 递归方式解决
     */
    ArrayList<Integer> tmp = new ArrayList<>();

    /**
     * 递归解法
     *
     * @param head
     * @return {@link int[]}
     */
    public int[] reverseBookList(ListNode head) {
        recur(head);
        int[] res = new int[tmp.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = tmp.get(i);
        }
        return res;
    }

    void recur(ListNode head) {

        if (head == null) {
            return;
        }

        recur(head.next);

        tmp.add(head.val);
    }

    /**
     * 辅助栈解法
     *
     * @param head
     * @return {@link int[]}
     */
    public int[] reverseBookList2(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<>();
        while (head != null) {
            // 入栈
            stack.addLast(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for (int i = 0; i < res.length; i++) {
            // 出栈
            res[i] = stack.removeLast();
        }
        return res;
    }

}